package db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.amkor.commons.util.db.MultiDBConnection;


public class SimpleDSFactory {
	
	private	 String MYSQL = "java:comp/env/jdbc/ds1";
	private	 String DB2   = "java:comp/env/jdbc/ds2";
	
/* 2013-05-14 (jeongyej) : MySQL DB Connection 를 생성한다. */	
	
	public Connection makeMySQLNewConnection() throws ClassNotFoundException, SQLException {
		
		Connection m_conn = MultiDBConnection.getConnection(MYSQL);
		
		return m_conn;
	}
	
/* 2013-05-14 (jeongyej) : DB2 DB Connection 를 생성한다. */	
	
	public Connection makeDB2NewConnection() throws ClassNotFoundException, SQLException {
		
		Connection m_conn = MultiDBConnection.getConnection(DB2);
		
		return m_conn;
	}
		
/* 2013-05-14 (jeongyej) : sql 구문과 함께 PreparedStatement 가져온다. */
	
	public PreparedStatement getPstmt(Connection m_conn, String sql) throws SQLException{
		return m_conn.prepareStatement(sql);		
	}
	
/** 2013-05-14 (jeongyej) : sql 업데이트 Transaction 를 실행한다. 
 * 
 * @param ps
 * @param isBatch
 * 	Batch Transaction 유무
 * 
 * @return
 */
	
	public boolean getResultUpdate(PreparedStatement m_psmt, boolean isBatch) throws SQLException{
		
		if(isBatch){
			return (m_psmt.executeBatch() == null)?false:true;
		}else{
			return (m_psmt.executeUpdate() == 0)?false:true;
		}
								
	}
	
/* 2013-05-14 (jeongyej) : flag 에 따라서 commit 혹은 rollback 를 실행한다. */
	
	public void writeSQL(boolean isSuccess, Connection m_conn) throws SQLException, Exception{
		if(isSuccess){
			m_conn.commit();
			m_conn = null;
		}else{
			m_conn.rollback();
		}
	}
	
/* 2013-05-14 (jeongyej) : DS 관련 자원을 close 한다. */	
	
	public void cleanup(ResultSet m_rs, PreparedStatement m_psmt, Connection m_conn) throws SQLException{
		if(m_rs != null)		m_rs.close();
		if(m_psmt != null) m_psmt.close();
		if(m_conn != null)	m_conn.close();
	}
	
}
